/* eslint-disable */
import $ from "jquery";
import EnvConf from "@/config/envConf.js";
import BaseUtil from "@/utils/baseUtil.js";

export default {
    data() {

        return {
            fileName: "",
        };
    },

    created() {

        const _this = this;

        this.$root.$on("fileParsed", (fileName) => {
            if (!_this.fileName) _this.fileName = fileName.substring(0, fileName.indexOf("."));
        });
    },

    methods: {

        saveFile(cb) {

            const _this = this;

            const urlParams = BaseUtil.paresUrlSearchStr();

            if (urlParams === null || !urlParams.hasOwnProperty("modelId")) {

                this.$message.error("无效的模型ID,请返回主页重试");

                return;
            }

            Editor.encodeProject(async (data) => {

                if (JSON.parse(data).res.length === 0) return;

                const zip = new JSZip();
                zip.file(_this.fileName, data);

                const content = zip.generate({
                    type: "uint8array",
                    compression: "DEFLATE",
                    compressionOptions: {
                        level: 9
                    }
                });

                const file = new Blob([content], { type: "text/plain" });

                const fileContent = new FormData();
                fileContent.append("file", file, _this.fileName + ".halo");
                fileContent.append("modelId", urlParams['modelId']);

                const envConf = EnvConf[process.env.NODE_ENV];
                const uploadFileUrl = `${envConf.baseUrl}:${envConf.port}${envConf.uploadFile}`;

                try {

                    const result = await _this.$http.query({
                        url: uploadFileUrl,
                        method: "POST",
                        data: fileContent,
                        contentType: false,
                        processData: false,
                    });

                    if (!result.success) {
                        _this.$message.error(result.errorMessage);
                        return;
                    }

                    const updateModelUrl = `${envConf.baseUrl}:${envConf.port}${envConf.updateModel}`;
                    const updateModeData = {
                        modelUrl: result.result.url,
                        modelSize: result.result.fileSize,
                        fileName: result.result.fileName,
                        modelId: urlParams.modelId,
                    };

                    try {

                        const updateRes = await _this.$http.ajQuery({
                            url: updateModelUrl,
                            method: "POST",
                            data: updateModeData,
                        });

                        if (updateRes.success) {

                            _this.$message.success("保存成功！");

                            if (cb)cb(result.result.url);

                        } else {
                            _this.$message.error(updateRes.errorMessage);
                        }

                    } catch (e) {
                       if (e.responseJSON)  _this.$message.error(e.status + ": " + e.responseJSON.errorMessage);
                    }

                } catch (e) {
                    if (e.responseJSON)  _this.$message.error(e.status + ": " + e.responseJSON.errorMessage);
                }

                // _this.download(content, "test" + ".halo", 'text/plain');
            });
        },

        myWorkZone () {
            location.href = "/player.html#/my-home-page";
        },

        pushFile () {

            this.saveFile(() => {

                const urlParams = BaseUtil.paresUrlSearchStr();

                location.href = "/player.html#/pub-model/" + urlParams.modelId;
            });
        },

        preView () {

            this.saveFile((modelUrl) => {

                const urlParams = BaseUtil.paresUrlSearchStr();

                window.open("/haloEditor/player/player.html?modelUrl=" + modelUrl, "_blank");
            });

        },

        download(text, name, type) {

            const a = document.createElement("a");

            const file = new Blob([text], { type: type });

            a.href = URL.createObjectURL(file);

            a.download = name;

            this.fake_click(a);
        },

        fake_click(obj) {
            const ev = document.createEvent("MouseEvents");

            ev.initMouseEvent(
                "click", true, false, window, 0, 0, 0, 0, 0
                , false, false, false, false, 0, null
            );

            obj.dispatchEvent(ev);
        },

        renameFile (e) {
            $(e.target).siblings().find("input").removeAttr("disabled");
            $(e.target).siblings().find("input").focus();
        },

        renameFileNameInput (e) {

            if (e.keyCode === 13) {

                $(e.target).attr("disabled", "disabled");

                this.fileName = $.trim($(e.target).val());
            }

        }
    }
}